package com.ymt.bpm.service.mobile;

import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.appboot.env.Caches;
import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.dao.Mapper;
import com.ymt.bpm.model.Const.Oplog;
import com.ymt.bpm.model.PUser;
import com.ymt.bpm.service.platform.cache.CacheService;
import com.ymt.bpm.service.platform.log.OpLogService;
import com.ymt.bpm.util.AES;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.JwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by Johnny on 2017/11/26.
 */
@Service
public class MAuthService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MDao dao;

    @Autowired
    private Environment env;

    @Autowired
    private CacheService cacheService;

    //@Autowired
    //private OpLogService oplog;

    public JSONObject login(String login, String password, long time, long expires) {
        JSONObject rtn = new JSONObject();
        PUser user = getByLogin(login);
        //JSONObject userJo = getUserJoByLogin(login);
        if (user==null) {
            rtn.put(Const.AJAX_RESULT, 0);
            rtn.put(Const.AJAX_MSG, "NO_USER");
        } else {
            if (DigestUtils.sha256Hex(password).equals(user.getPassword())) {
                String token = JwtUtil.token(user.getTenantId(), user.getLoginName(), user.getDisplayName(), user.getLang(), time, expires);
//                String token = JwtUtil.token(userJo.containsKey(Const.TENANT_ID) ? userJo.getIntValue(Const.TENANT_ID) : 0,
//                        userJo.getString(Const.LOGINNAME), userJo.getString(Const.DISPLAYNAME),
//                        userJo.getString(Const.LANG), time, expires);
                rtn.put(Const.DISPLAYNAME, user.getDisplayName());
                //rtn.put(Const.DISPLAYNAME, userJo.getString(Const.DISPLAYNAME));
                rtn.put(Const.JWT_TOKEN, token);
                rtn.put(Const.AJAX_RESULT, 1);

                //记录日志
                //oplog.bizlog(user.getTenantId()>0 ? String.valueOf(user.getTenantId()) : null, user.getLoginName(), user.getDisplayName(), null, Oplog.OP.LOGIN,  Oplog.CODE.PLATFORM_MOBILE, "");
            } else {
                rtn.put(Const.AJAX_RESULT, 0);
                rtn.put(Const.AJAX_MSG, "WRONG_PWD");
            }
        }
        return rtn;
    }

    /**
     * 为钉钉用户登录
     * @param login
     * @param authkeydd
     * @param time
     * @param expires
     * @return
     */
    public JSONObject logindd(String login, String authkeydd, long time, long expires) {
        JSONObject rtn = new JSONObject();
        PUser user = getByLogin(login);
        //JSONObject userJo = getUserJoByLogin(login);
        if (user==null) {
            rtn.put(Const.AJAX_RESULT, 0);
            rtn.put(Const.AJAX_MSG, "NO_USER");
        } else {
            //set DINGTALK_DIRECT_LOGIN in dd-mapp
            if (("DINGTALK_DIRECT_LOGIN").equals(AES.decrypt(authkeydd))) {
                String token = JwtUtil.token(user.getTenantId(), user.getLoginName(), user.getDisplayName(), user.getLang(), time, expires);
//                String token = JwtUtil.token(userJo.containsKey(Const.TENANT_ID) ? userJo.getIntValue(Const.TENANT_ID) : 0,
//                        userJo.getString(Const.LOGINNAME), userJo.getString(Const.DISPLAYNAME),
//                        userJo.getString(Const.LANG), time, expires);
                rtn.put(Const.DISPLAYNAME, user.getDisplayName());
                //rtn.put(Const.DISPLAYNAME, userJo.getString(Const.DISPLAYNAME));
                rtn.put(Const.JWT_TOKEN, token);
                rtn.put(Const.AJAX_RESULT, 1);

                //记录日志
                //oplog.bizlog(user.getTenantId()>0 ? String.valueOf(user.getTenantId()) : null, user.getLoginName(), user.getDisplayName(), null, Oplog.OP.LOGIN,  Oplog.CODE.PLATFORM_MOBILE, "");
            } else {
                rtn.put(Const.AJAX_RESULT, 0);
                rtn.put(Const.AJAX_MSG, "WRONG_PWD");
            }
        }
        return rtn;
    }

    public JSONObject registerdd(Map<String, String> map) {
        String tenantIdEnc = map.get("tidenc");
        String tenantId = tenantIdEnc!=null && tenantIdEnc.length()>0 ? AES.decrypt(tenantIdEnc) : null;
        String loginName = map.get("loginName");
        String realName = map.get("realName");
        String password = map.get("password");
        String authkeydd = map.get("authkeydd");
        String email = map.get("email");
        String mobile = map.get("mobile");
        JSONObject rtn = new JSONObject();
        int rs = 0;
        if (("DINGTALK_DIRECT_LOGIN").equals(AES.decrypt(authkeydd))) {
            map.put(Const.TENANT_ID, tenantId);
            PUser user = dao.selectOne(Mapper.PUserMapper, "selectByMobile", map);
            if (user!=null) { //存在
                //检查 tenantId
                boolean update = true;
                if (user.getTenantId()!=null && user.getTenantId()>0 && String.valueOf(user.getTenantId()).equalsIgnoreCase(tenantId)) {
                    // do nothing
                } else {
                    update = false;
                }
                //检查用户名
                if (!StringUtils.isEmpty(user.getLoginName()) && !user.getLoginName().equalsIgnoreCase(loginName)) {
                    update = false;
                    rtn.put("msg", "LOGINNAME_USED"); //用户名已被占用
                }
                if (update) {
                    user.setLoginName(loginName);
                    user.setPassword(DigestUtils.sha256Hex(password));
                    user.setUserId(loginName);
                    user.setIsvalid("1");
                    rs += dao.update(Mapper.PUserMapper, "updateByMobileSelective", user);
                }
            } else {//不存在
                user = new PUser();
                if (tenantId!=null && StringUtils.isNumeric(tenantId)) {
                    user.setTenantId(Integer.parseInt(tenantId));
                }
                user.setUserId(loginName);
                user.setLoginName(loginName);
                user.setStatus("00"); //人员状态 00-新注册 在职10 休假11 离职12
                user.setRealName(realName);
                user.setDisplayName(realName+"("+loginName+")");
                user.setPassword(DigestUtils.sha256Hex(password));
                user.setEmail(email);
                user.setMobile(mobile);
                user.setUserType("0"); //人员类型 普通员工0 外协人员1
                user.setIsvalid("1"); //是否有效 是1 否0
                rs = dao.insert(Mapper.PUserMapper, "insertSelective", user);
            }
        }
        rtn.put(Const.AJAX_RESULT, rs);
        return rtn;
    }

    //@Cacheable(value= Caches.USER, key="#login")
    public PUser getByLogin(String login) {
        String cacheKey = login;
        PUser user = cacheService.get(Caches.USER, cacheKey);
        if (user==null) {
            user = dao.selectOne(Mapper.PUserMapper, "selectByLogin", login);
            if (user!=null) {
                cacheService.put(Caches.USER, cacheKey, user);
            }
        }

        return user;
    }

    /*@Cacheable(value= Caches.USER, key="#login")
    public JSONObject getUserJoByLogin(String login) {
        PUser user = dao.selectOne(Mapper.PUserMapper, "selectByLogin", login);
        return (JSONObject) JSONObject.toJSON(user);
    }*/

    //@Cacheable
    public long getExpires() {
        String timeoutStr = env.getProperty("bpmp.session-timeout", "30");
        return Integer.parseInt(timeoutStr) * 60000L;
    }

    //@Cacheable
    public long getExpiresForMobile() {
        String timeoutStr = env.getProperty("bpmp.mobile.session-timeout", "30");
        return Integer.parseInt(timeoutStr) * 60000L;
    }

}
